package middleware

import (
	"fmt"
	"geek-cloud-native/chapter04-0925/global"
	"github.com/julienschmidt/httprouter"
	"net"
	"net/http"
)

func LoggerMiddleware(router httprouter.Handle) httprouter.Handle {
	return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		remoteIP := getRemoteIP(w, r, ps)
		global.Logger.Method = r.Method
		global.Logger.Path = r.URL.Path
		global.Logger.RemoteAddr = r.RemoteAddr
		global.Logger.Status = http.StatusOK
		global.Logger.Info(remoteIP)
		router(w, r, ps)
	}
}

func getRemoteIP(w http.ResponseWriter, req *http.Request, _ httprouter.Params) string {
	ip, _, err := net.SplitHostPort(req.RemoteAddr)
	if err != nil {
		//return nil, fmt.Errorf("userip: %q is not IP:port", req.RemoteAddr)
		fmt.Fprintf(w, "userip: %q is not IP:port", req.RemoteAddr)
	}

	return ip
}
